<?php defined('SYSPATH') or die('No direct script access.');

class Model_Company extends ORM
{  
    protected $_table_name = 'companies';
    protected $_reload_on_wakeup = false;
    protected static $_current = null;             // current
    
    public static function check_domain($domain)
    {
        $company = ORM::factory('company')
                        ->where('domain', '=', $domain)
                        ->find();
        if ($company->loaded()) {
            return false;   
        }
        return true;    
    }
    
    public function get_company_by_domain($domain)
    {
        $company = ORM::factory('company')
                    ->where('domain', '=', $domain)
                    ->find();
        if (!$company->loaded()) {
            throw new Model_Exception('Такой компании нет');      
        }
        return $company;
    }
    
    public function add_company($domain, $phone)
    {
        /*if (!Valid::url($url)) {
            throw new Model_Exception('Некорректный адрес магазина');
        } */
        
        $domain      = Security::xss_clean($domain);
        $phone       = Security::xss_clean($phone);
        
        try {
            $this->domain = $domain;
            $this->phone  = $phone;
            $this->save();
        } catch (Database_Exception $e) {
            if (strstr($e->getMessage(), 'Duplicate entry') !== false) {
                throw new Model_Exception('Компания с таким доменом уже зарегистрирована');
            } else {
                throw new Model_Exception($e->getMessage());
            }
        }
        
        return $this;  
    }
    
    public function edit_company($name, $domain, $phone)
    {       
        /*if (!Valid::url($url)) {
            throw new Model_Exception('Некорректный адрес магазина');
        }*/
        
        $this->name   = $name;
        $this->domain = $domain;
        $this->phone  = $phone;
        $this->save();
    } 
    
    public function set_as_current()
    {
        self::$_current = $this; 
    } 
    
    public function get_current()
    {
        return self::$_current;
    }
}